using Avalonia.Media.Imaging;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Threading.Tasks;
using Material.Icons;
using System.IO;
using System;
using Avalonia.Platform.Storage;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using MathPlus.Features.ScreenShot;

namespace MathPlus.Features.LatexOCR;

public partial class LatexOCRViewModel : DemoPageBase
{
    private IStorageProvider? StorageProvider
    {
        get
        {
            if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                return desktop.MainWindow?.StorageProvider;
            }
            return null;
        }
    }

    [ObservableProperty]
    private string? recognizedText;

    [ObservableProperty]
    private Bitmap? selectedImage;

    [ObservableProperty]
    private Bitmap? processedImage;

    public LatexOCRViewModel() : base("LaTeX OCR", MaterialIconKind.Function, -150)
    {
    }

    [RelayCommand]
    private async Task CaptureScreen()
    {
        var screenshot = new ScreenShotView();
        var result = await screenshot.ShowDialog<string>(
            Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop
                ? desktop.MainWindow : null);

        if (!string.IsNullOrEmpty(result))
        {
            await LoadImage(result);
            await ProcessImage(result);
        }
    }

    [RelayCommand]
    private async Task SelectImage()
    {
        var storageProvider = StorageProvider;
        if (storageProvider == null) return;

        var files = await storageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
        {
            Title = "选择图片",
            AllowMultiple = false,
            FileTypeFilter = new[]
            {
                new FilePickerFileType("图片")
                {
                    Patterns = new[] { "*.jpg", "*.jpeg", "*.png", "*.bmp" },
                    MimeTypes = new[] { "image/jpeg", "image/png", "image/bmp" }
                }
            }
        });

        var file = files.FirstOrDefault();
        if (file == null) return;

        await LoadImage(file.Path.LocalPath);
        await ProcessImage(file.Path.LocalPath);
    }

    private async Task LoadImage(string path)
    {
        if (File.Exists(path))
        {
            using var stream = File.OpenRead(path);
            SelectedImage = new Bitmap(stream);
            
            // 清除之前的处理结果
            ProcessedImage = null;
            RecognizedText = string.Empty;
        }
    }

    private async Task ProcessImage(string path)
    {
        // TODO: 实现 LaTeX OCR 处理逻辑
        RecognizedText = "LaTeX OCR processing...";
        
        // 暂时复制原图作为处理后的图像
        if (SelectedImage != null)
        {
            ProcessedImage = SelectedImage;
        }
    }

    [RelayCommand]
    private async Task SaveResult()
    {
        if (string.IsNullOrEmpty(RecognizedText)) return;

        var storageProvider = StorageProvider;
        if (storageProvider == null) return;

        var file = await storageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
        {
            Title = "保存识别结果",
            DefaultExtension = ".txt",
            FileTypeChoices = new[]
            {
                new FilePickerFileType("文本文件")
                {
                    Patterns = new[] { "*.txt" },
                    MimeTypes = new[] { "text/plain" }
                }
            }
        });

        if (file == null) return;

        await File.WriteAllTextAsync(file.Path.LocalPath, RecognizedText);
    }

    [RelayCommand]
    private async Task ExportDoc()
    {
        if (string.IsNullOrEmpty(RecognizedText)) return;

        var storageProvider = StorageProvider;
        if (storageProvider == null) return;

        var file = await storageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
        {
            Title = "导出文档",
            DefaultExtension = ".tex",
            FileTypeChoices = new[]
            {
                new FilePickerFileType("LaTeX 文件")
                {
                    Patterns = new[] { "*.tex" },
                    MimeTypes = new[] { "text/x-tex" }
                }
            }
        });

        if (file == null) return;

        // TODO: 添加 LaTeX 文档模板
        var content = $@"\documentclass{{article}}
\usepackage{{amsmath}}
\usepackage{{amssymb}}
\begin{{document}}

{RecognizedText}

\end{{document}}";

        await File.WriteAllTextAsync(file.Path.LocalPath, content);
    }
}
